using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace EasyEditorGUI.Editor
{
    public class DropDownWindow : PopupWindowContent
    {
        public event Action<int> onSelectionChanged
        {
            add => _listView.onSelectionChanged += value;
            remove => _listView.onSelectionChanged -= value;
        }
        
        readonly Vector2 _size;
        readonly SearchField _searchField = new SearchField();
        protected readonly ListView _listView;

        public DropDownWindow(Vector2 size, IEnumerable<string> items)
        {
            _size = size;
            _listView = new ListView(items);
            _listView.onSelectionChanged += _ => EditorApplication.delayCall = editorWindow.Close;
        }

        public void Show(in Rect rect)
        {
            PopupWindow.Show(rect, this);
        }

        public override Vector2 GetWindowSize()
        {
            return _size;
        }

        public override void OnGUI(Rect rect)
        {
            EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
            RenderToolbar();
            EditorGUILayout.EndHorizontal();

            float offset = EditorStyles.toolbar.fixedHeight;
            rect.y += offset;
            rect.height -= offset;
            _listView.OnGUI(rect);
        }

        protected virtual void RenderToolbar()
        {
            _listView.searchString = _searchField.OnToolbarGUI(_listView.searchString);
        }
    }
}